// pages/lifeService/repairReport/index.js
const app = getApp();
var topOpacity = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 组件参数设置，传递到组件
    defaultData: {
      title: "报事报修", // 导航栏标题
      showHome: false, //是否显示回到首页按钮
      showBack: true, //是否显示返回按钮
      showLogo: false, //是否显示logo
      bgColor: 'transparent',
      goUrl:'/pages/lifeService/managementFee/menu'
    },
    baseUrl: app.baseUrl,
    version: app.globalData.version,
    navBarHeight: app.globalData.navBarHeight,
    showArray: [
      [],
      [],
      [],
      []
    ], //展示数据
    array: [
      [],
      [],
      [],
      []
    ], // 数据数组，分别对应三级联动的数据
    city: ['请选择房号', '', '', ''], // 默认选中的值
    curBuildId: 0, //当前楼栋Id
    //组团
    groupList: [],
    //单元
    buildingList: [],
    //楼栋
    unitList: [],
    //房号
    roomList: [],
    qy: '请选择区域',
    qyList: [{
        city_id: '0',
        city_name: '室内'
      },
      {
        city_id: '1',
        city_name: '公区'
      }
    ],
    time: '请选择上门时间',
    partPro: '',
    noteMaxLen: 300,
    sendImgArr: [], //已上传图片集合
    images: [], //上传图片集合
    isHeightModeArr: [],
    imgMax: 100, //上传图片的大小限制M
    showTime: true,
    orderType: "请选择类型",
    orderTypeList: [],
    orderTypeIndex: -1,
    familyIdArr: [],
    familyId: '',
    userId: '',
    shareTitle: '',
    shareImg: '',
  },
  onPageScroll(t) {
    if (t.scrollTop < 40) {
      topOpacity = 0
      if (this.data.topOpacity != 0) {
        this.setData({
          topOpacity: 0
        })
      }
    } else if (t.scrollTop >= 40) {
      if (topOpacity <= 1) {
        topOpacity = t.scrollTop / 100 - .4
      } else {
        topOpacity = 1
      }
      if (topOpacity <= 1) {
        this.setData({
          topOpacity: topOpacity
        })
      }
    }
  },
  //留言
  // partProVal(e) {
  //   this.setData({
  //     partPro: e.detail.value
  //   })
  // },
  //描述输入框
  partPro: function (e) {
    var value = e.detail.value,
      len = parseInt(value.length);
    if (len > this.data.noteMaxLen) return;
    this.setData({
      partPro: e.detail.value,
      currentNoteLen: len //当前字数
    })
  },
  //选择您所在的区域
  qyChange(e) {
    let that = this;
    let id = that.data.qyList[e.detail.value].city_id;
    that.setData({
      qy: that.data.qyList[e.detail.value].city_name,
    });
    if (id == "0") {
      that.setData({
        showTime: true
      })
    } else {
      that.setData({
        showTime: false
      })
    }
  },
  orderTypeChange(e) {
    let that = this;
    let orderTypeIndex = e.detail.value;
    let orderTypeList = that.data.orderTypeList;
    that.setData({
      orderTypeIndex: orderTypeIndex,
      orderType: orderTypeList[orderTypeIndex].name
    })
  },
  bindChange: function (e) {
    const val = e.detail.value;
    console.log("val:", val)
    console.log("this.data.array:", this.data.array)
    this.setData({
      city: [
        this.data.array[0][val[0]].name,
        this.data.array[1][val[1]].name,
        this.data.array[2][val[2]].name,
        this.data.array[3][val[3]].name
      ],
      familyId: this.data.familyIdArr[val[0]]
    });
    console.log("familyId:", this.data.familyId)
  },
  bindColumnChange: function (e) {
    let that = this;
    const col = e.detail.column;
    const val = e.detail.value;
    const array = that.data.array;
    var showArray = that.data.showArray;
    var groupList = that.data.groupList;
    var buildingList = that.data.buildingList;
    var unitList = that.data.unitList;
    var roomList = that.data.roomList;
    // 根据选择的建筑更新单元和楼层数据
    var buildingListNew = [];
    var unitListNew = [];
    var roomListNew = [];
    buildingListNew[0] = buildingList[val];
    unitListNew[0] = unitList[val];
    roomListNew[0] = roomList[val];

    showArray[0] = groupList.map((item) => {
      return item.name
    })
    showArray[1] = buildingListNew.map((item) => {
      return item.name
    })
    showArray[2] = unitListNew.map((item) => {
      return item.name
    })
    showArray[3] = roomListNew.map((item) => {
      return item.name
    })

    array[0] = groupList;
    array[1] = buildingListNew;
    array[2] = unitListNew;
    array[3] = roomListNew;
    console.log("arrar:", array)

    that.setData({
      array,
      showArray
    })
  },
  //选择截止日期
  onPickerChange(e) {
    let that = this;
    that.setData({
      time: e.detail.value
    });
  },
  //上传图片
  upLoadImg: function (e) {
    let that = this;
    wx.chooseImage({
      count: 9 - that.data.images.length,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: res => {
        let tempFilePaths = res.tempFilePaths;
        let images = that.data.images;
        let isHeightModeArr = that.data.isHeightModeArr;
        if ((images.length + tempFilePaths.length) > 9) {
          app.showTip("最多只能上传9张");
          return;

        }
        for (var item in res.tempFilePaths) {
          that.data.images.push(res.tempFilePaths[item]);
          isHeightModeArr.push(false);
          tempFilePaths = that.data.images;
        }
        //限制上传图片大小为5M,所有图片少于5M才能上传
        let size = res.tempFiles.every(item => {
          return item.size <= parseInt(that.data.imgMax) * 1024 * 1024
        })
        if (size) {
          that.setData({
            images: tempFilePaths,
            isHeightModeArr: isHeightModeArr
          })
        } else {
          app.showTip("上传图片不能大于" + that.data.imgMax + "M哦");

        }
      }
    })
  },

  // 图片加载后判断图片宽高比例
  oneImageLoad(e) {
    const {
      width,
      height,
    } = e.detail
    let index = e.currentTarget.dataset.index;
    let isHeightModeArr = this.data.isHeightModeArr;
    if (height >= width) {
      isHeightModeArr[index] = true;
      this.setData({
        isHeightModeArr
      })
    }

  },
  //删除图片
  delFile(e) {
    let that = this;
    let delNum = e.currentTarget.dataset.index;
    let images = that.data.images;
    let isHeightModeArr = that.data.isHeightModeArr;
    images.splice(delNum, 1);
    isHeightModeArr.splice(delNum, 1);
    that.setData({
      images: images,
      isHeightModeArr: isHeightModeArr
    })
  },
  // 预览图片
  previewImage(e) {
    let that = this,
      imgsrc = e.currentTarget.dataset.presrc,
      arr = that.data.images
    //console.log(preArr)
    wx.previewImage({
      current: imgsrc,
      urls: arr
    })
  },
  //提交
  tj() {
    let that = this;
    let roomNum = that.data.city;
    let qy = that.data.qy;
    let partPro = that.data.partPro;
    let time = that.data.time;
    let orderTypeList = that.data.orderTypeList;
    let orderTypeIndex = that.data.orderTypeIndex;

    var qyId = -1;
    if (qy == "室内") {
      qyId = 0;
    } else {
      qyId = 1;
    }



    if (roomNum[0] == "请选择房号") {
      app.showTip("请选择房号");
      return;
    }
    console.log(qy)
    if (qy == "请选择区域") {
      app.showTip("请选择区域");
      return;
    }
    if (time == "请选择上门时间") {
      app.showTip("请选择上门时间");
      return;
    }
    if (orderTypeIndex == -1) {
      app.showTip("请选择类型");
      return;
    }
    if (partPro == "") {
      app.showTip("请输入问题描述");
      return;
    }
    wx.showLoading({
      title: '信息提交中...'
    });
    //这里需要组装orderType的值
    var orderType = {
      orderTypeId: orderTypeList[orderTypeIndex].orderTypeId,
      orderDetailTypeId: orderTypeList[orderTypeIndex].orderDetailTypeId,
      id: orderTypeList[orderTypeIndex].id
    }

    var data = {
      userId: that.data.userId,
      appointmentTime: Date.parse(time),
      familyId: that.data.familyId,
      eventDescription: partPro,
      areaType: qyId,
      orderType: orderType
    };
    if (that.data.images.length > 0) {
      //上传了图片
      for (var i = 0; i < that.data.images.length; i++) {
        wx.uploadFile({
          url: that.data.baseUrl + "api/uploadImg.php", //服务器接口
          method: 'POST',
          filePath: that.data.images[i],
          header: {
            'content-type': 'multipart/form-data'
          },
          name: 'file', //服务器定义的Key值
          formData: {},
          success: function (res) {
            if (res.data) {
              var sendImgArr = that.data.sendImgArr;
              sendImgArr.push(res.data);
              that.setData({
                sendImgArr: sendImgArr
              });

              if (that.data.images.length == that.data.sendImgArr.length) {
                data.eventPic = that.data.sendImgArr.join(',');
                wx.request({
                  url: that.data.baseUrl + 'api/getApiData.php',
                  method: 'POST',
                  data: {
                    'apiUrl': '/openapi/maintOrder/v1/create',
                    'data': JSON.stringify(data)
                  },
                  header: {
                    'content-type': 'application/x-www-form-urlencoded'
                  },
                  success: function (res) {
                    if (res.data.status == 1) {
                       //调用最终上传数据
                      wx.hideLoading();
                      app.showTip("提交成功");
                      wx.redirectTo({
                        url: '/pages/lifeService/repairReport/recordList?backHome=true',
                      })
                    }
                  },
                  fail: function (res) {
                     //调用最终上传数据
                    wx.hideLoading();
                    app.showTip('服务器繁忙,请稍候重试');
                  }
                });
              }
            } else {
               //调用最终上传数据
               wx.hideLoading();
              app.showTip('服务器保存图片失败,请刷新页面重试');
            }
          },
          fail: function () {
            wx.hideLoading();
            app.showTip('服务器繁忙,请稍候重试');
          }
        });
      }

    } else {
      wx.request({
        url: that.data.baseUrl + 'api/getApiData.php',
        method: 'POST',
        data: {
          'apiUrl': '/openapi/maintOrder/v1/create',
          'data': JSON.stringify(data)
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          wx.hideLoading();
          if (res.data.status == 1) {
            app.showTip("提交成功")
            wx.redirectTo({
              url: '/pages/lifeService/repairReport/recordList?backHome=true',
            })
          }
        },
        fail: function (res) {
          wx.hideLoading();
          app.showTip('服务器繁忙,请稍候重试');
        }
      });

    }


  },
  goRecordList(){
    wx.navigateTo({
      url: '/pages/lifeService/repairReport/recordList',
    })
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let that = this;
    //后台更新楼栋单元房号信息
    //that.changeInfo(0, 3001, 0, 0);
    var data = {};
    //获取缓存中的openid"oZYOb4ktAvmrb5TsIPBHlrGEKcZg"//
    var openid = wx.getStorageSync('ly24_openid');
    let orderTypeList = that.data.orderTypeList;
    var array = that.data.array;
    var showArray = that.data.showArray;
    var groupList = that.data.groupList;
    var buildingList = that.data.buildingList;
    var unitList = that.data.unitList;
    var roomList = that.data.roomList;
    var familyIdArr = that.data.familyIdArr;

    var buildingListNew = [];
    var unitListNew = [];
    var roomListNew = [];
    wx.request({
      url: that.data.baseUrl + 'api/getUserId.php',
      method: 'POST',
      data: {
        'openid': openid,
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        if (res.data.status == 1) {
          var userId = res.data.userId;
          var data1 = {
            "userId": userId
          }
          that.setData({
            userId: userId
          })
          wx.request({
            url: that.data.baseUrl + 'api/getApiData.php',
            method: 'POST',
            data: {
              'apiUrl': '/openapi/family/v1/queryUserFamilies',
              'data': JSON.stringify(data1)
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            success: function (res) {
              if (res.data.status == 1) {
                var homeInfoList = res.data.data;
                if (homeInfoList.length == 0) {
                  app.showTip('您当前不是业主或家人身份哦');
                  setTimeout(function () {
                    wx.navigateBack({
                      delta: 1
                    });
                  }, 1500);
                  return;
                } else {

                  for (var i = 0; i < homeInfoList.length; i++) {
                    var groupObj = {};
                    var buildingObj = {};
                    var unitObj = {};
                    var roomObj = {};
                    groupObj.id = homeInfoList[i].groupId;
                    groupObj.name = homeInfoList[i].groupName;
                    buildingObj.groupId = homeInfoList[i].groupId;
                    buildingObj.id = homeInfoList[i].buildingId;
                    buildingObj.name = homeInfoList[i].buildingName;
                    unitObj.groupId = homeInfoList[i].groupId;
                    unitObj.buildingId = homeInfoList[i].buildingId;
                    unitObj.id = homeInfoList[i].unitId;
                    unitObj.name = homeInfoList[i].unitName;
                    roomObj.groupId = homeInfoList[i].groupId;
                    roomObj.buildingId = homeInfoList[i].buildingId;
                    roomObj.unitId = homeInfoList[i].unitId;
                    roomObj.id = homeInfoList[i].roomId;
                    roomObj.name = homeInfoList[i].roomName;
                    groupList.push(groupObj);
                    buildingList.push(buildingObj);
                    unitList.push(unitObj);
                    roomList.push(roomObj);
                    familyIdArr.push(homeInfoList[i].id)
                  }

                  buildingListNew[0] = buildingList[0];
                  unitListNew[0] = unitList[0];
                  roomListNew[0] = roomList[0];

                  array[0] = groupList;
                  array[1] = buildingListNew;
                  array[2] = unitListNew;
                  array[3] = roomListNew;
                  console.log("arrar:", array)
                  showArray[0] = groupList.map((item) => {
                    return item.name
                  })
                  showArray[1] = buildingListNew.map((item) => {
                    return item.name
                  })
                  showArray[2] = unitListNew.map((item) => {
                    return item.name
                  })
                  showArray[3] = roomListNew.map((item) => {
                    return item.name
                  })
                  that.setData({
                    groupList: groupList,
                    buildingList: buildingList,
                    unitList: unitList,
                    roomList: roomList,
                    array: array,
                    showArray: showArray,
                    familyIdArr: familyIdArr
                  });
                }

              }
            },
            fail: function (res) {}
          });
        }
      },
      fail: function (res) {}
    });
    wx.request({
      url: that.data.baseUrl + 'api/getApiData.php',
      method: 'POST',
      data: {
        'apiUrl': '/openapi/maintOrder/v1/types',
        'data': JSON.stringify(data)
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        if (res.data.status == 1) {
          orderTypeList = res.data.data;

          that.setData({
            orderTypeList
          })
        }
      },
      fail: function (res) {}
    });
     //调用分享
     that.getShareInfo();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },
//获取微信分享信息
getShareInfo() {
  var that = this;
  wx.request({
    url: that.data.baseUrl + 'getShareInfo.php',
    method: 'POST',
    data: {

    },
    header: {
      'content-type': 'application/x-www-form-urlencoded'
    },
    success: function (res) {
      that.setData({
        shareTitle: res.data.shareTitle,
        shareImg: res.data.shareImg
      });
    },
    fail: function (res) {}
  });
},
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    var that = this;
    return {
      title: that.data.shareTitle,
      path: '/pages/index/index',
      imageUrl: that.data.shareImg,
      success: function (res) {

      },
      fail: function (res) {

      }
    }
  }
})